'use strict';

const Subscription = require('egg').Subscription;
const dayjs = require('dayjs');

class LeaseSubscription extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      cron: '0 1 0 * * *',
      type: 'all',
      immediate: true,
    };
  }

  async subscribe() {
    await this.updateLeaseExpire();
    await this.updateLeaseEffect();
  }
  // 批量找出过期的租约并修改
  async updateLeaseExpire() {
    const { ctx } = this;
    const leases = await ctx.service.lease.findAll({ status: 2, endTime: new Date(dayjs(Date.now()).format('YYYY-MM-DD')) });
    if (leases && leases.length) {
      for (let i = 0, len = leases.length; i < len; i++) {
        await ctx.service.lease.update({ status: 3, id: leases[i].id });
        await ctx.service.house.update({ status: 4, id: leases[i].houseId });
      }
    }
  }

  // 批量找出生效的租约并修改
  async updateLeaseEffect() {
    const { ctx } = this;
    const leases = await ctx.service.lease.findAll({ status: 1, startTime: new Date(dayjs(Date.now()).format('YYYY-MM-DD')) });
    if (leases && leases.length) {
      for (let i = 0, len = leases.length; i < len; i++) {
        await ctx.service.lease.update({ status: 2, id: leases[i].id });
        await ctx.service.house.update({ status: 5, id: leases[i].houseId });
      }
    }
  }
}

module.exports = LeaseSubscription;
